package gameServer.view;

import com.alibaba.fastjson.JSONObject;
import gameServer.model.Message;
import gameServer.model.Player;
import gameServer.model.Poker;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

import com.alibaba.fastjson.JSON;

/**
 * 服务器主窗体，用于开启服务器
 */
public class ServerMainFrame {

    //标识玩家自动增长
    public int index = 0;
    //声明玩家列表用于存储创建的所有玩家
    public List<Player> players = new ArrayList<>();
    //全部扑克牌列表
    public List<Poker> allPokers = new ArrayList<>();
    //存放3张底牌
    public List<Poker> lordPokers = new ArrayList<>();
    //牌局的进展步骤
    public int step = 0;

    public ServerMainFrame() {
        createPokers();
        try {
            ServerSocket serverSocket = new ServerSocket(8888);
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("服务器端" + socket);
                //处理客户端发来的消息
                AcceptThread acceptThread = new AcceptThread(socket);//服务器端接收消息的线程
                acceptThread.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //服务器端用于处理接收客户端发送的消息
    class AcceptThread extends Thread {
        public Socket socket;

        public AcceptThread(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            //取消息
            try {
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                while (true) {
                    //读取客户端信息并显示
                    String message = dataInputStream.readUTF();

                    /**创建玩家
                     * 玩家 持有 扑克
                     * 扑克类 & 玩家类
                     */
                    if (step == 0) {
                        //依据用户名创建具体玩家
                        Player player = new Player(index++, message);
                        //给玩家绑定与服务器端通信的socket
                        player.setSocket(socket);
                        players.add(player);

                        //玩家人数
                        System.out.println(message + "-用户已上线");
                        System.out.println("在线人数：" + players.size());
                        //System.out.println("玩家其他信息：" + players);

                        //三位玩家到齐后发牌
                        if (players.size() == 3) {
                            //发牌
                            dealPokers();
                            step = 1;
                        }
                    } else if (step == 1) {
                        //接收抢地主信息
                        System.out.println("接收抢地主信息...");
                        JSONObject messageJsonObject = JSON.parseObject(message);
                        int typeid = messageJsonObject.getInteger("typeid");
                        int playerid = messageJsonObject.getInteger("playerid");
                        String content = messageJsonObject.getString("content");
                        //抢地主
                        if (typeid == 2) {
                            //组建消息对象，添加地主牌
                            Message sendMessage = new Message(typeid, playerid, content, lordPokers);
                            message = JSON.toJSONString(sendMessage);
                            step = 2;
                        }
                        //群发消息到客户端
                        sendMessageToClient(message);
                    } else if (step == 2) {
                        //出牌/不出牌/游戏结束
                        sendMessageToClient(message);
                    }

                }
            } catch (IOException e) {
                System.out.println("ServerError:" + e.getMessage());
            }
        }
    }

    //群发消息到客户端
    public void sendMessageToClient(String message) {
        for (int i = 0; i < players.size(); i++) {
            DataOutputStream dataOutputStream;
            try {
                dataOutputStream = new DataOutputStream(players.get(i).getSocket().getOutputStream());
                dataOutputStream.writeUTF(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //创建扑克牌
    public void createPokers() {
        //大小王
        Poker jokerA = new Poker(0, "JOKER-A", 17);
        Poker jokerB = new Poker(0, "JOKER-B", 16);
        allPokers.add(jokerA);
        allPokers.add(jokerB);
        //其他扑克牌
        String[] names = new String[]{"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
        String[] colors = new String[]{"Spade", "Heart", "Club", "Diamond"};//黑桃，红桃，梅花，方块

        int id = 2;
        int num = 15;
        for (int i = 0; i < names.length; i++) {
            for (int j = 0; j < colors.length; j++) {
                Poker poker = new Poker(id++, colors[j] + names[i], num);
                allPokers.add(poker);
            }
            num--;
        }
        //洗牌
        Collections.shuffle(allPokers);
        System.out.println("扑克数量：" + allPokers.size());
    }

    //发牌
    public void dealPokers() {
        //留3张底牌
        lordPokers.add(allPokers.get(0));
        lordPokers.add(allPokers.get(1));
        lordPokers.add(allPokers.get(2));
        // 发给三个玩家
        for (int i = 3; i < allPokers.size(); i++) {
            // 依次分发给三个玩家
            if (i % 3 == 0) {
                players.get(0).getPokers().add(allPokers.get(i));
            } else if (i % 3 == 1) {
                players.get(1).getPokers().add(allPokers.get(i));
            } else {
                players.get(2).getPokers().add(allPokers.get(i));
            }
        }
        System.out.println("players:" + players);
        //将玩家牌信息发送到client进行扑克牌列表显示
        for (int i = 0; i < players.size(); i++) {
            try {
                DataOutputStream dataOutputStream = new DataOutputStream(players.get(i).getSocket().getOutputStream());
                String jsonString = JSON.toJSONString(players);
                System.out.println("服务器的JSON串：" + jsonString);
                dataOutputStream.writeUTF(jsonString);

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
